//
//  QXNRegisterViewController.m
//  快医
//
//  Created by sdos on 2017/3/9.
//  Copyright © 2017年 乔现宁. All rights reserved.
//

#import "QXNRegisterViewController.h"
#import "Masonry.h"
#import <SMS_SDK/SMSSDK.h>
#import <MOBFoundation/MOBFoundation.h>
#import <MBProgressHUD.h>

#define RGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]

// 宏定义 随机颜色
#define RandomColor RGBColor(arc4random_uniform(255), arc4random_uniform(255), arc4random_uniform(255))



@interface QXNRegisterViewController ()<UITextFieldDelegate>

//手机号
@property(nonatomic,strong)UITextField *phoneNumber;
//验证码
@property(nonatomic,strong)UITextField *verfi;
//获取验证码倒计时
@property(nonatomic,strong)UIButton *timeBT;
//点击同意协议
@property(nonatomic,strong)UIButton *boxBT;
//用户协议lable
@property(nonatomic,strong)UILabel *agreeeLB;
//注册
@property(nonatomic,strong)UIButton *registBT;

@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,assign)NSInteger secondes;

@property (copy,nonatomic) NSString* savedNumber;
@property (assign,nonatomic) NSInteger timeNum;
@end

@implementation QXNRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setnav];
    [self setupUI];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.timer invalidate];
    self.timer = nil;
}

- (void)setnav
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"home_nav_button_back"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = RGBColor(66, 197, 195);
    self.title = @"注册";
}
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupUI
{
    //添加手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(missKeyboard)];
    [self.view addGestureRecognizer:pan];
    //添加控件
    [self.view addSubview:self.phoneNumber];
    [self.view addSubview:self.verfi];
    [self.view addSubview:self.timeBT];
    [self.view addSubview:self.boxBT];
    [self.view addSubview:self.agreeeLB];
    [self.view addSubview:self.registBT];
    
    //约束
    //手机号
    [self.phoneNumber mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(64+50);
        make.leading.equalTo(self.view).offset(20);
        make.trailing.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(30);
    }];
    //输入验证码
    [self.verfi mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(200, 30));
        make.leading.equalTo(self.phoneNumber);
        make.top.mas_equalTo(self.phoneNumber.mas_bottom).offset(50);
    }];
    //获取验证码按钮
    [self.timeBT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.verfi);
        make.leading.equalTo(self.verfi.mas_trailing).offset(20);
        make.size.mas_equalTo(CGSizeMake(140, 30));
        
    }];
    
    //协议
    [self.agreeeLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(180, 20));
        make.top.mas_equalTo(self.verfi.mas_bottom).offset(50);
        make.centerX.equalTo(self.view);
        
    }];
    //点击同意协议按钮
    [self.boxBT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.agreeeLB);
        make.trailing.mas_equalTo(self.agreeeLB.mas_leading).offset(-10);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    //注册按钮
    [self.registBT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.leading.equalTo(self.view).offset(20);
        make.trailing.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(40);
        make.top.mas_equalTo(self.agreeeLB.mas_bottom).offset(30);
    }];
}

#pragma mark
#pragma mark -手势
- (void)missKeyboard {
    //辞去第一响应者
    [self.verfi resignFirstResponder];
}
#pragma mark
#pragma mark - 设置控件属性
- (UITextField *)phoneNumber
{
    if (_phoneNumber == nil) {
        _phoneNumber = [[UITextField alloc] init];
        _phoneNumber.placeholder = @"请输入您的手机号码";
        _phoneNumber.clearButtonMode = UITextFieldViewModeWhileEditing;
        _phoneNumber.borderStyle = UITextBorderStyleRoundedRect;
        //将键盘设置为电话键盘
        _phoneNumber.keyboardType = UIKeyboardTypePhonePad;
        //添加监听事件
        [_phoneNumber addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _phoneNumber;
}
#pragma
#pragma-添加监听事件
- (void)valueChanged:(UITextField*)sender
{

   
    _timeBT.enabled = sender.text.length;
    _timeBT.selected = sender.text.length;
    
    }




- (UITextField *)verfi
{
    if (_verfi == nil) {
        _verfi = [[UITextField alloc] init];
        _verfi.delegate = self;
        _verfi.placeholder = @"请输入验证码";
        _verfi.clearButtonMode = UITextFieldViewModeWhileEditing;
        _verfi.borderStyle = UITextBorderStyleRoundedRect;
        _verfi.keyboardType = UIKeyboardTypeNumberPad;
    }
    return _verfi;
}

- (UIButton *)timeBT
{
    if (_timeBT == nil) {
        _timeBT = [[UIButton alloc] init];
        [_timeBT setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_timeBT setBackgroundImage:[UIImage imageNamed:@"e5e5e5"] forState:UIControlStateNormal];
        [_timeBT setBackgroundImage:[UIImage imageNamed:@"nav"] forState:UIControlStateSelected];
        _timeBT.layer.cornerRadius = 3;
        _timeBT.layer.masksToBounds = YES;
        _timeBT.titleLabel.font = [UIFont systemFontOfSize:16];
        [_timeBT addTarget:self action:@selector(clicktimeBT:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _timeBT;
}


- (UIButton *)boxBT
{
    if (_boxBT == nil) {
        _boxBT = [[UIButton alloc] init];
        [_boxBT setImage:[UIImage imageNamed:@"illness_rb_img_nor.png"] forState:UIControlStateNormal];
        [_boxBT setImage:[UIImage imageNamed:@"illness_rb_img_sel.png"] forState:UIControlStateSelected];
        [_boxBT addTarget:self action:@selector(boxBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _boxBT;
}

- (UILabel *)agreeeLB
{
    if (_agreeeLB == nil) {
        _agreeeLB = [[UILabel alloc] init];
        _agreeeLB.font = [UIFont systemFontOfSize:13];
        
        NSString *agreeText = @"本人同意并阅读 用户协议";
        NSMutableAttributedString *arrM = [[NSMutableAttributedString alloc] initWithString:agreeText];
        //截取字符串
        NSRange range = [agreeText rangeOfString:@"用户协议"];
        [arrM addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],
                              NSForegroundColorAttributeName:RGBColor(50, 170, 240)
                              } range:range];
        _agreeeLB.attributedText = arrM;
    }
    return _agreeeLB;
}

- (UIButton *)registBT
{
    if (_registBT == nil) {
        _registBT = [[UIButton alloc] init];
        [_registBT setTitle:@"请阅读用户协议" forState:UIControlStateNormal];
        [_registBT setTitle:@"注册" forState:UIControlStateSelected];
        [_registBT setBackgroundImage:[UIImage imageNamed:@"nav"] forState:UIControlStateSelected];
        [_registBT  setBackgroundImage:[UIImage imageNamed:@"e5e5e5"] forState:UIControlStateNormal];
        [_registBT setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _registBT.titleLabel.font = [UIFont systemFontOfSize:20];
        [_registBT addTarget:self action:@selector(clickregistBT:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registBT;
}


#pragma mark
#pragma mark - 点击获取验证码事件
- (void)clicktimeBT:(UIButton*)sender
{
    NSLog(@"发送验证码");
    sender.enabled = NO;
    sender.selected = NO;
    //获取输入内容
    NSString* phoneNumber =[NSString stringWithFormat:@"%@", self.phoneNumber.text];
    //判断号码
    if(phoneNumber.length != 11)
    {
        return;
    }
    self.savedNumber = phoneNumber;
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:phoneNumber zone:@"86" customIdentifier:nil result:^(NSError *error) {
        if (error) {
            NSLog(@"获取验证码失败:%@",error);
        }
    }];
    
    self.timeNum = 10;
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(runtimer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    _timer = timer;
}
- (void)runtimer
{
    if (self.timeNum < 0) {
        _timeBT.enabled = YES;
        _timeBT.selected = YES;
        //取消定时器 重新获取时,保证1s变化 即调用一次
        [_timer invalidate];
        [_timeBT setTitle:[NSString stringWithFormat:@"重新获取验证码"] forState:UIControlStateSelected];
        _timeBT.titleLabel.font = [UIFont systemFontOfSize:13];
        return;
    } else {
        _timeBT.selected = NO;
        _timeBT.enabled = NO;
        [_timeBT setTitle:[NSString stringWithFormat:@"%zd秒后重新发送",self.timeNum] forState:UIControlStateNormal];
        [_timeBT setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.timeNum = self.timeNum - 1;
        
    }
}

#pragma mark
#pragma mark -点击注册事件
- (void)clickregistBT:(UIButton*)sender
{
    
    [self.view endEditing:YES];
    NSLog(@"注册了");
    sender.enabled = NO;
    //验证结果
    NSString *verifyCode   = self.verfi.text ;
    if (verifyCode.length != 4) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        
        // Set the text mode to show only text.
        hud.mode = MBProgressHUDModeText;
        hud.label.text = NSLocalizedString(@"注册码错误!", @"HUD message title");
        // Move to bottm center.
        hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
        
        [hud hideAnimated:YES afterDelay:1.f];
        sender.enabled = YES;
        return;
    }
    //  提交验证码
//    [SMSSDK commitVerificationCode:verifyCode phoneNumber:self.savedNumber zone:@"86" result:^(SMSSDKUserInfo *userInfo, NSError *error) {
//       if ( error == nil)
//       {
//          
//       }else{
//           NSLog(@"%@",error);
//       }
//    }];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    
    // Set the custom view mode to show any view.
    hud.mode = MBProgressHUDModeCustomView;
    // Set an image view with a checkmark.
    UIImage *image = [[UIImage imageNamed:@"Checkmark"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    hud.customView = [[UIImageView alloc] initWithImage:image];
    // Looks a bit nicer if we make it square.
    hud.square = YES;
    // Optional label text.
    hud.label.text = NSLocalizedString(@"注册成功", @"HUD done title");
    
    [hud hideAnimated:YES afterDelay:3.f];
    sender.enabled = YES;
    [UIView animateWithDuration:0.1 delay:2 options:UIViewAnimationOptionCurveEaseOut animations:^{
        
    }  completion:^(BOOL finished) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
}

#pragma
#pragma-添加选中按钮点击事件
- (void)boxBtnClick:(UIButton*)sender
{
    sender.selected = !sender.selected;
    self.registBT.selected = sender.selected;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark
#pragma mark -textField的代理方法
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    //手动呼出键盘
    [self.verfi becomeFirstResponder];
    NSTimeInterval animationDuration = 0.5;
    [UIView beginAnimations:@"keyBoard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动
    self.view.frame = CGRectMake(0, -50,self.view.frame.size.width , self.view.frame.size.height);
    [UIView commitAnimations];
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    [UIView beginAnimations:@"reset" context:nil];
    [UIView setAnimationDuration:0.3];
    //恢复屏幕
    self.view.frame = CGRectMake(0, 64, self.view.frame.size.width,  self.view.frame.size.height);
    [UIView commitAnimations];
}


@end
